# !/usr/bin/env python
# -*- coding:utf-8 -*-
import sys
sys.path.append("..")
from modelDb.tourists import touristsModel
from modelDb.tourists_actions import touristsActionsModel
from modelPortrait.portrait import portrait
from pykafka import KafkaClient
import json
from config.db import kafka as kafkaConf
from config.db import zookeeper as zookeeperConf
import time

class portraitMain(object):
    def __init__(self):
        """
        初始化
        """
        pass



    def start(self):
        num = 0
        while True:
            try:
                # todo kafka 获取数据
                tourists = touristsModel()
                touristsActions = touristsActionsModel()
                portraitData = None
                for ii in range(0, 100):
                    portraitData = touristsActions.selectPortrait(num=num)
                    if not portraitData: num +=1
                    else:break


                if not portraitData:
                    time.sleep(60)
                    continue


                #kafka
                self.client = KafkaClient(hosts=kafkaConf.get("host"))  # 这里连接多个客户端
                kafka_topic = self.client.topics[ kafkaConf.get("topics") ]

                with kafka_topic.get_sync_producer() as producer:
                    for data in portraitData:
                        try:
                            resultPort = portrait(data).getDictData()
                            jsonData = json.dumps(resultPort)
                            print jsonData
                            producer.produce(jsonData)
                            # 修改状态
                            touristsActions.updateEtl(data=data, data_status=3)
                        except Exception, e:
                            print "================================="
                            print e
                            print json.dumps(data)


            except Exception, e:
                print e

if __name__ == "__main__":
    portraitMain().start()